package com.ovopark.organize.server.common.exception;



import com.ovopark.organize.common.base.BaseResult;
import com.ovopark.organize.server.expection.ResultCode;
import com.ovopark.organize.server.expection.ResultCodeInfo;
import com.ovopark.organize.server.expection.SysErrorException;
import com.ovopark.organize.server.model.response.JsonNewResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @ClassName GlobalExceptionHandler
 * @Description //全局异常处理
 * @Author yuyinghua@ovopark.com
 * @Date 2019/6/27 16:29
 * @Version 1.0
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 已知异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value=CommonException.class)
    public BaseResult errorHandler3 (CommonException ex) {
        String code = ex.getCode();
        if (code == null){
            return BaseResult.error("1",ex.getMessage());
        }else {
            if (StringUtils.equals(ex.getCode(),"1")){
                log.error(ex.toString());
            }
            return BaseResult.error(code,ex.getMessage());
        }
    }


    /**
     * 请求方式错误
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value= {HttpMediaTypeNotSupportedException.class,
            HttpRequestMethodNotSupportedException.class
    })
    public BaseResult errorHandler5 (Exception ex) {
        return BaseResult.error("-1","PARAM_ERROR");
    }



    @ResponseBody
    @ExceptionHandler( value = {
            BindException.class,
            MethodArgumentNotValidException.class,
            MethodArgumentTypeMismatchException.class,
    })
    public BaseResult errorHandler6 (Exception ex) {
        return BaseResult.error("-1","PARAM_ERROR");
    }




    /**
     * 全局获取异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value=Exception.class)
    public BaseResult errorHandler2 (Exception ex) {
        log.error(ex.getMessage(),ex);
        return BaseResult.error("1","ERROR");
    }



    @ExceptionHandler(value = SysErrorException.class)
    @ResponseBody
    public JsonNewResult<Object> defaultErrorHandler(final HttpServletRequest req, HttpServletResponse resp, final Exception e) throws Exception {

        logger.error("拦截到错误", e);
        /*  使用response返回    */
        resp.setStatus(HttpStatus.OK.value()); //设置状态码
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        resp.setCharacterEncoding("UTF-8"); //避免乱码
        resp.setHeader("Cache-Control", "no-cache, must-revalidate");

        ResultCodeInfo resultCodeInfo = null;
        String cause = null;
        if(e instanceof SysErrorException) {
            SysErrorException de = (SysErrorException) e;
            cause = de.getMessage();
//            logger.error("_trace_id:"+ HttpContext.getTraceId()+";SysErrorException Error reason!" + de.getMessage(), de);
            resultCodeInfo = de.getResultCodeInfo();
            if(null == resultCodeInfo){
                resultCodeInfo = ResultCode.FAILURE;
            }
            return JsonNewResult.error(resultCodeInfo);
        }

        throw e;
    }


}